<template>
  <div class="admin-users">
    <!-- 顶部导航 -->
    <header class="admin-header">
      <div class="header-left">
        <h1>校园快递管理系统</h1>
      </div>
      <div class="header-right">
        <span class="welcome-text">欢迎，{{ currentAdmin && currentAdmin.phone ? currentAdmin.phone : '' }}</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </header>
    
    <!-- 侧边栏 -->
    <aside class="sidebar">
      <nav class="sidebar-nav">
        <router-link to="/admin/dashboard" class="nav-item">
          <i class="icon-home">🏠</i>
          <span>仪表盘</span>
        </router-link>
        <router-link to="/admin/users" class="nav-item active">
          <i class="icon-users">👥</i>
          <span>用户管理</span>
        </router-link>
        <router-link to="/admin/parcels" class="nav-item">
          <i class="icon-parcel">📦</i>
          <span>包裹管理</span>
        </router-link>
        <router-link to="/admin/logs" class="nav-item">
          <i class="icon-logs">📋</i>
          <span>操作日志</span>
        </router-link>
      </nav>
    </aside>
    
    <!-- 主内容区 -->
    <main class="main-content">
      <div class="users-management">
        <div class="page-header">
          <h2>用户管理</h2>
          <div class="header-actions">
            <div class="search-box">
              <input 
                type="text" 
                v-model="searchQuery" 
                placeholder="搜索手机号或昵称..."
                @input="handleSearch"
              >
              <button class="search-btn">🔍</button>
            </div>
            <select v-model="roleFilter" @change="handleFilter">
              <option value="">全部角色</option>
              <option value="order_user">普通用户</option>
              <option value="courier">快递员</option>
              <option value="both">两者都是</option>
              <option value="admin">管理员</option>
            </select>
          </div>
        </div>
        
        <!-- 用户列表 -->
        <div class="users-table-container">
          <div v-if="loading" class="loading">加载中...</div>
          <div v-else-if="users.length === 0" class="no-data">暂无用户数据</div>
          <table v-else class="users-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>手机号</th>
                <th>昵称</th>
                <th>角色</th>
                <th>登录方式</th>
                <th>手机验证</th>
                <th>注册时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.id">
                <td>{{ user.id }}</td>
                <td>{{ user.phone || '未设置' }}</td>
                <td>{{ user.nickname || '未设置' }}</td>
                <td>
                  <span class="role-tag" :class="getRoleClass(user.role)">
                    {{ getRoleText(user.role) }}
                  </span>
                </td>
                <td>{{ getUserMethodText(user.login_method) }}</td>
                <td>
                  <span class="status-tag" :class="user.is_phone_verified ? 'verified' : 'unverified'">
                    {{ user.is_phone_verified ? '已验证' : '未验证' }}
                  </span>
                </td>
                <td>{{ formatTime(user.created_at) }}</td>
                <td>
                  <button class="btn-edit" @click="editUser(user)">编辑</button>
                  <button class="btn-delete" @click="confirmDelete(user)">
                    删除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination" v-if="!loading && users.length > 0">
          <button 
            class="page-btn" 
            @click="changePage(currentPage - 1)" 
            :disabled="currentPage === 1"
          >
            上一页
          </button>
          <span class="page-info">
            第 {{ currentPage }} / {{ totalPages }} 页
          </span>
          <button 
            class="page-btn" 
            @click="changePage(currentPage + 1)" 
            :disabled="currentPage === totalPages"
          >
            下一页
          </button>
        </div>
      </div>
    </main>
    
    <!-- 编辑用户弹窗 -->
    <div class="modal" v-if="showEditModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>编辑用户</h3>
          <button class="close-btn" @click="closeModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="updateUser">
            <div class="form-group">
              <label>手机号</label>
              <input type="tel" v-model="editingUser.phone" disabled>
            </div>
            
            <div class="form-group">
              <label>昵称</label>
              <input type="text" v-model="editingUser.nickname" placeholder="请输入昵称">
            </div>
            
            <div class="form-group">
              <label>角色</label>
              <select v-model="editingUser.role">
                <option value="order_user">普通用户</option>
                <option value="courier">快递员</option>
                <option value="both">两者都是</option>
                <option value="admin">管理员</option>
              </select>
            </div>
            
            <div class="form-group">
              <label>手机验证状态</label>
              <select v-model="editingUser.is_phone_verified">
                <option :value="1">已验证</option>
                <option :value="0">未验证</option>
              </select>
            </div>
            
            <div v-if="editError" class="error-message">
              {{ editError }}
            </div>
            
            <div class="modal-footer">
              <button type="button" class="btn-cancel" @click="closeModal">取消</button>
              <button type="submit" class="btn-save" :disabled="saving">
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AdminUserManagement',
  data() {
    return {
      loading: false,
      users: [],
      searchQuery: '',
      roleFilter: '',
      currentPage: 1,
      pageSize: 10,
      totalPages: 1,
      currentAdmin: null,
      showEditModal: false,
      editingUser: {},
      editError: '',
      saving: false
    };
  },
  async beforeMount() {
    this.checkLoginStatus();
    await this.loadUsers();
  },
  methods: {
    checkLoginStatus() {
      const adminInfo = localStorage.getItem('adminInfo');
      if (adminInfo) {
        try {
          this.currentAdmin = JSON.parse(adminInfo);
        } catch (error) {
          console.error('解析管理员信息失败:', error);
          this.logout();
        }
      } else {
        this.logout();
      }
    },
    
    async loadUsers() {
      this.loading = true;
      try {
        const response = await fetch(`/api/admin/users?page=${this.currentPage}&pageSize=${this.pageSize}&search=${this.searchQuery}&role=${this.roleFilter}`, {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          if (data.success) {
            this.users = data.data.users;
            this.totalPages = Math.ceil(data.data.total / this.pageSize);
          }
        }
      } catch (error) {
        console.error('加载用户列表失败:', error);
      } finally {
        this.loading = false;
      }
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.loadUsers();
    },
    
    handleFilter() {
      this.currentPage = 1;
      this.loadUsers();
    },
    
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page;
        this.loadUsers();
      }
    },
    
    getRoleClass(role) {
      const roleClasses = {
        'order_user': 'role-user',
        'courier': 'role-courier',
        'both': 'role-both',
        'admin': 'role-admin'
      };
      return roleClasses[role] || '';
    },
    
    getRoleText(role) {
      const roleTexts = {
        'order_user': '普通用户',
        'courier': '快递员',
        'both': '两者都是',
        'admin': '管理员'
      };
      return roleTexts[role] || '未知';
    },
    
    getUserMethodText(method) {
      const methodTexts = {
        'wechat': '微信登录',
        'phone': '手机号登录'
      };
      return methodTexts[method] || '未知';
    },
    
    formatTime(timeString) {
      if (!timeString) return '';
      const date = new Date(timeString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    editUser(user) {
      this.editingUser = { ...user };
      this.editError = '';
      this.showEditModal = true;
    },
    
    async updateUser() {
      this.editError = '';
      this.saving = true;
      
      try {
        const response = await fetch(`/api/admin/users/${this.editingUser.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
          },
          body: JSON.stringify({
            nickname: this.editingUser.nickname,
            role: this.editingUser.role,
            is_phone_verified: this.editingUser.is_phone_verified
          })
        });
        
        const result = await response.json();
        
        if (result.success) {
          this.closeModal();
          this.loadUsers();
        } else {
          this.editError = result.message || '更新失败';
        }
      } catch (error) {
        console.error('更新用户失败:', error);
        this.editError = '网络错误，请稍后重试';
      } finally {
        this.saving = false;
      }
    },
    
    confirmDelete(user) {
      if (confirm(`确定要删除用户 ${user.phone || user.id} 吗？`)) {
        this.deleteUser(user.id);
      }
    },
    
    async deleteUser(userId) {
      try {
        const response = await fetch(`/api/admin/users/${userId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
          }
        });
        
        const result = await response.json();
        if (result.success) {
          this.loadUsers();
        } else {
          alert('删除失败: ' + (result.message || '未知错误'));
        }
      } catch (error) {
        console.error('删除用户失败:', error);
        alert('网络错误，请稍后重试');
      }
    },
    
    closeModal() {
      this.showEditModal = false;
      this.editingUser = {};
      this.editError = '';
    },
    
    handleLogout() {
      if (confirm('确定要退出登录吗？')) {
        this.logout();
      }
    },
    
    logout() {
      localStorage.removeItem('adminToken');
      localStorage.removeItem('adminInfo');
      this.$router.push('/admin/login');
    }
  }
};
</script>

<style scoped>
/* 管理员布局共享样式 */
.admin-header,
.sidebar,
.main-content {
  box-sizing: border-box;
}

.admin-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  z-index: 1000;
}

.header-left h1 {
  font-size: 20px;
  color: #333;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.welcome-text {
  color: #666;
}

.logout-btn {
  padding: 8px 16px;
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.logout-btn:hover {
  background: #ff3838;
}

.sidebar {
  width: 200px;
  background: #2c3e50;
  color: white;
  margin-top: 60px;
  position: fixed;
  height: calc(100vh - 60px);
  overflow-y: auto;
}

.sidebar-nav {
  padding: 20px 0;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  color: #ecf0f1;
  text-decoration: none;
  transition: background 0.3s;
}

.nav-item:hover {
  background: #34495e;
}

.nav-item.active {
  background: #667eea;
}

.nav-item i {
  margin-right: 10px;
  font-size: 18px;
}

.main-content {
  flex: 1;
  margin-left: 200px;
  margin-top: 60px;
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 60px);
  background: #f5f7fa;
}

/* 用户管理特有样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-box {
  display: flex;
  align-items: center;
}

.search-box input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  width: 250px;
}

.search-btn {
  padding: 8px 15px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.header-actions select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

/* 表格样式 */
.users-table-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
}

.users-table {
  width: 100%;
  border-collapse: collapse;
}

.users-table th,
.users-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ecf0f1;
}

.users-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

/* 标签样式 */
.role-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.role-user { background: #3498db; color: white; }
.role-courier { background: #2ecc71; color: white; }
.role-both { background: #f39c12; color: white; }
.role-admin { background: #e74c3c; color: white; }

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-tag.verified { background: #2ecc71; color: white; }
.status-tag.unverified { background: #95a5a6; color: white; }

/* 按钮样式 */
.btn-edit,
.btn-delete {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 5px;
  font-size: 14px;
}

.btn-edit { background: #3498db; color: white; }
.btn-edit:hover { background: #2980b9; }

.btn-delete { background: #e74c3c; color: white; }
.btn-delete:hover { background: #c0392b; }

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 15px;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:hover:not(:disabled) {
  background: #f8f9fa;
}

.page-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-info {
  color: #666;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ecf0f1;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.form-group input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.error-message {
  background: #fee;
  color: #c33;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #ecf0f1;
}

.btn-cancel,
.btn-save {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.btn-cancel { background: #95a5a6; color: white; }
.btn-cancel:hover { background: #7f8c8d; }

.btn-save { background: #27ae60; color: white; }
.btn-save:hover:not(:disabled) { background: #229954; }

.btn-save:disabled {
  background: #95a5a6;
  cursor: not-allowed;
}
</style>